var ajaxStarted = false;

$(document).ready(function(){
  $('#supplierTable').tablesorter({
    headers :{
      3 :{sorter:false},
      4 :{sorter:false}
    }
  });
  
  $(document).on("click",'#supplierTable tbody tr td:nth-last-of-type(1)',deleteTdClick);
  $('#addSupplier').click(AddSupClick);
});

function deleteTdClick() {
  if(!confirm("Wollen Sie diesen Lieferant wirklich löschen?"))
    return;
  
  if(!ajaxStarted)
  {
    ajaxStarted=true;
    $(this).empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    var td = this;
    $.post("ajax/updateSupplier.php",{action:"delete",supplier:$(this).attr("supplier")}).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
        $(td).closest('tr').fadeTo(400,0,function(){$(this).remove();});
      }
      else
      {
        $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/delete.png",
                       "width":"20px",
                       "alt":"X"}));
        alert(jsonData.message);
      }
    }).fail(function(){
      $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}

function AddSupClick() {
  if(!ajaxStarted)
  {
    ajaxStarted=true;
    $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    
    $.post("ajax/updateSupplier.php",$('#newForm').serialize() + "&" + $.param({action:"add"})).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
        $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty();
        $('#supplierTable tbody').append(jsonData.message);
      }
      else
      {
        $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
        alert(jsonData.message);
      }
    }).fail(function(){
      $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}